package com.buydeem.share.customjson.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Objects;

/**
 * @author zengchao
 * @version 1.0.0
 * @ClassName BigDecimalSerialize.java
 * @Description TODO
 * @createTime 2021年06月23日 21:31:00
 */
public class BigDecimalSerialize extends JsonSerializer<BigDecimal> implements ContextualSerializer {
    private DecimalFormat df;
    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null){
            gen.writeNull();
        }else {
            if (df == null){
                gen.writeNumber(value.setScale(2,BigDecimal.ROUND_HALF_UP));
            }else {
                gen.writeString(df.format(value));
            }
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        //判断beanProperty是不是空
        if (property == null){
            return prov.findNullValueSerializer(property);
        }
        //判断类型是否是BigDecimal
        if (Objects.equals(property.getType().getRawClass(),BigDecimal.class)){
            JacksonBigDecimal annotation = property.getAnnotation(JacksonBigDecimal.class);
            if (annotation != null){
                String pattern = annotation.pattern();
                df = new DecimalFormat(pattern);
                return this;
            }
        }
        return prov.findValueSerializer (property.getType (), property);
    }
}
